/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.spring.app.genpostagelabel;

//import com.utilibill.db.Db_OptusSCPEnquire;
//import com.utilibill.mail.MailClient;
//import com.utilibill.optus.ws.wsgserviceorderservice.WsgServiceOrderService;
////import com.utilibill.schedular.jobs.UtbJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//package com.utilibill.schedular.jobs.exclusive.models;
/**
 *
 * @author Usman
 */
/**
 *
 * @author ashwani
 */
public class GenPostageLabel implements ColumnIndexes, ExcelConstants, ItemConstants {

    /**
     * @param args the command line arguments
     */
    private static final String itemListFilePath = "./files/resources/ItemList.txt";
    private static final int MAX_BUYER_TRANS = 1000;
    private String databaseUrl;
    //private Db_OptusSCPEnquire db;
    //private WsgServiceOrderService sos;
    private String emailServer;
    private String username;
    private String password;
    private String folder;
    private String job_business_contact;
    private String fromAddress;
    private String fromDisplayName;
    private String smtpServer;
    private String mailSubject;
    //private MailClient mail;
    private String mailSkipFrom;
    private String persistantRoot;
    private String archiveFolder;
    private List emails;
    private boolean ifTesting = true;
    private String destFileName = "";
    private String destItemListFileName = "";
    public static ArrayList<Item> items = new ArrayList<Item>();
    public static HashMap<String, Item> itemMap = new HashMap<String, Item>();

    private boolean loadItemList() {

        try {
            File itemListFile = new File(itemListFilePath);
            if (itemListFile == null) {
                System.err.println("Failed to load item list file");
                return false;
            }
          //Path path = Paths.get(itemListFilePath);
            String current = new java.io.File(".").getCanonicalPath();
            System.out.println("Current dir:" + current);
            BufferedReader br = new BufferedReader(new FileReader(itemListFile));
            String lne;
            ArrayList<String> lines = new ArrayList<String>();
            while ((lne = br.readLine()) != null) {
            	lines.add(lne);
            }
            br.close();
            
            if (lines == null) {
                System.err.println("Can't retrieve files");
                return false;
            }
            System.out.println("total items found = <" + lines.size() + ">");
            if (lines.size() > 0) {
                for (String line : lines) {
                    System.out.println("line = <" + line + ">");
                    String[] lineBrakup = line.split("#");
                    if (lineBrakup.length == 3) {
                        System.out.println("itemno=<" + lineBrakup[0]
                                + ">,itemDesc=<" + lineBrakup[1] + ">,itemCode=<"
                                + lineBrakup[2] + ">");
                        Item item = new Item(lineBrakup[0], lineBrakup[1], lineBrakup[2]);
                        items.add(item);
                        itemMap.put(lineBrakup[0], item);
                    } else {
                        System.err.println("Invalid line in item list <" + line + ">");
                        throw new Exception("Invalid line in item list");
                    }
                }
                System.out.println("Total items found in list = <" + items.size() + ">");
            } else {
                System.err.println("Can't retrieve files");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean initialize() {
        try {
            persistantRoot = new java.io.File(".").getCanonicalPath() + File.separator + "files";
            System.out.println("Persistent root = <" + persistantRoot + ">");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //persistantRoot = "D:\\ashwani jain\\Google_Drive\\Google Drive\\Ebay\\PostMe";

        if (persistantRoot != null && !persistantRoot.endsWith("\\")) {
            persistantRoot = persistantRoot + "\\";
        }

        archiveFolder = persistantRoot + "Archive";

        File archiveFolder = new File(this.archiveFolder);
        if (!archiveFolder.exists()) {
            archiveFolder.mkdirs();
        }


        //load available item list
        return loadItemList();







//        db = new Db_OptusSCPEnquire(databaseUrl);
//        sos = new WsgServiceOrderService();
//        mail = new MailClient();
        //return true;
    }

    public ArrayList createPostItemList(ArrayList buyers, String destFile) {

        ArrayList postItemList = new ArrayList();
        System.out.println("Entry in createPostItemList");
        if (buyers == null) {
            System.out.println("Error!! buyers list is empty");
            return null;
        }

        int totalLabels = buyers.size();
        System.out.println("Total Labels Required - " + totalLabels);
        for (int i = 0; i < totalLabels; i++) {
            String itemNo = "";
            String itemName = "";
            String name = "";
            String userId = "";
            String state = "";
            String quantity = "";
            String itemCode = "";
            PostItemList postItem = new PostItemList();

            state = ((BuyerDetail) buyers.get(i)).getState();
            userId = ((BuyerDetail) buyers.get(i)).getUserId();
            name = ((BuyerDetail) buyers.get(i)).getFullName();
            itemName = ((BuyerDetail) buyers.get(i)).getItemTitle();
            itemNo = ((BuyerDetail) buyers.get(i)).getItemId();
            quantity = ((BuyerDetail) buyers.get(i)).getQuantity();

            if (state == null || state.equals("")) {
                System.out.println("Error!! state is empty");
                return null;
            } else {
                postItem.setState(state);
            }


            if (userId == null || userId.equals("")) {
                System.out.println("Error!! userId is empty");
                return null;
            } else {
                postItem.setUserId(userId);
            }
            if (name == null || name.equals("")) {
                System.out.println("Error!! name is empty");
                return null;
            } else {
                postItem.setFullName(name);
            }

            if (itemName == null || itemName.equals("")) {
                System.out.println("Error!! itemName is empty");
                return null;
            } else {
                postItem.setItemName(itemName);
            }
            if (itemNo == null || itemNo.equals("")) {
                System.out.println("Error!! itemNo is empty");
                return null;
            } else {
                itemCode = Item.getItemCode(itemNo, itemName);
                if (itemCode != null && !itemCode.equals("")) {
                    postItem.setItemCode(itemCode);
                }
            }
            if (quantity == null || quantity.equals("")) {
                System.out.println("Error!! quantity is empty");
                return null;
            } else {
                postItem.setItemQuantity(quantity);
            }

            String newLine = System.getProperty("line.separator");
            String listItemEntry = name + " - " + itemCode + " - " + quantity;
            listItemEntry += newLine;
            listItemEntry += userId + " - " + state;
            postItem.setItemListEntry(listItemEntry);
            if (postItem != null) {
                postItemList.add(postItem);
                ((BuyerDetail) buyers.get(i)).setItemCode(itemCode + "-" + quantity);
                System.out.println("Buyer item code = " + ((BuyerDetail) buyers.get(i)).getItemCode());
            }
        }

        return postItemList;

    }

//    public boolean printPostageLabels(ArrayList postItems, String destFile) {
//    }
    public boolean printPostItemList(ArrayList postItems, String destFile) {
        boolean retVal = true;
        try {
            int totalItems = postItems.size();
            System.out.println("Total postItems to print - " + totalItems);

            if (destFile == null || destFile.equalsIgnoreCase("")) {
                System.out.println("Error!! Dest File Name is empty");
                return false;
            }

            System.out.println("Creating empty output file");
            File output = new File(destFile);

            /*Write Excel File Data*/
            HSSFWorkbook hwb = new HSSFWorkbook();
            HSSFSheet sheet = hwb.createSheet("list");

            //set the format for sheet
            sheet.setMargin(HSSFSheet.BottomMargin, ITEMLIST_BOTTOMMARGIN_VAL);
            sheet.setMargin(HSSFSheet.TopMargin, ITEMLIST_TOPMARGIN_VAL);
            sheet.setMargin(HSSFSheet.LeftMargin, ITEMLIST_LEFTMARGIN_VAL);
            sheet.setMargin(HSSFSheet.RightMargin, ITEMLIST_RIGHTMARGIN_VAL);
            //sheet.setMargin(HSSFSheet.HeaderMargin, HEADERMARGIN_VAL);
            //sheet.setMargin(HSSFSheet.FooterMargin, FOOTERMARGIN_VAL);

            HSSFPrintSetup printSetup = sheet.getPrintSetup();
            printSetup.setHeaderMargin(ITEMLIST_HEADERMARGIN_VAL);
            printSetup.setPaperSize(PAPERSIZE);
            printSetup.setFooterMargin(ITEMLIST_FOOTERMARGIN_VAL);

            sheet.setColumnWidth(0, ITEMLIST_CELL_WIDTH);
            sheet.setColumnWidth(1, ITEMLIST_CELL_WIDTH);
            sheet.setDefaultRowHeight((short) ITEMLIST_CELL_HEIGHT);
            HSSFCellStyle cellStyle = hwb.createCellStyle();

            HSSFFont cellFont = hwb.createFont();
            //Bold character
            cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //Aerial font
            cellFont.setFontName(this.ITEMLIST_CELL_FONT_NAME);
            //Font Size 12
            cellFont.setFontHeightInPoints((short) this.ITEMLIST_CELL_FONT_SIZE);


            //set cell font
            cellStyle.setFont(cellFont);
            //set cell alignment
            //cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //cell wrap text
            cellStyle.setWrapText(true);
            //set cell width & height

            //Print two array elements in one column
            int totalRows = (int) totalItems / 2 + (int) totalItems % 2;
            int itemCounter = 0;
            for (int rowCount = 0; rowCount < totalRows; rowCount++) {
                HSSFRow row = sheet.createRow((short) rowCount);
                row.setHeightInPoints(CELL_HEIGHT_IN_POINTS);
                for (int colCount = 0; colCount < 2 && itemCounter < totalItems; itemCounter++, colCount++) {
                    HSSFCell cell = row.createCell(colCount);
                    cell.setCellStyle(cellStyle);
                    if (postItems.get(itemCounter) != null && !postItems.get(itemCounter).toString().equals("")) {
                        HSSFRichTextString richTextItem = new HSSFRichTextString(((PostItemList) (postItems.get(itemCounter))).getItemListEntry());
                        System.out.println("PostItem in Rich Text format = " + richTextItem);
                        cell.setCellValue(richTextItem);
                    }

                }
            }


            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(output);
                hwb.write(fos);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;

    }

    public ArrayList createPostageLables(ArrayList buyers, String destFile) {
        return createLabel(buyers, destFile);
    }

    public ArrayList createLabel(ArrayList buyers, String destFile) {

        ArrayList labels = new ArrayList();
        int counter = 0;
        try {
            String newLine = System.getProperty("line.separator");

            if (buyers == null) {
                System.out.println("Error!! buyers list is empty");
                return null;
            }

            int totalLabels = buyers.size();
            System.out.println("Total Labels Required - " + totalLabels);

            //Merge records
            for (int i = 0; i < totalLabels; i++) {
                String fullName = "";
                String address1 = "";
                String address2 = "";
                String city = "";
                String state = "";
                String postcode = "";
                String country = "";
                String label = "";
                String itemCodeWithQty = "";
                fullName = ((BuyerDetail) buyers.get(i)).getFullName();
                address1 = ((BuyerDetail) buyers.get(i)).getAddress1();
                if (address1 == null || address1.length() <= 0) {
                    address1 = "";
                }
                address2 = ((BuyerDetail) buyers.get(i)).getAddress2();
                if (address2 == null || address2.length() <= 0) {
                    address2 = "";
                }
                city = ((BuyerDetail) buyers.get(i)).getCity();
                state = ((BuyerDetail) buyers.get(i)).getState();
                country = ((BuyerDetail) buyers.get(i)).getCountry();
                postcode = ((BuyerDetail) buyers.get(i)).getPostcode();
                itemCodeWithQty = ((BuyerDetail) buyers.get(i)).getItemCode();

                System.out.print("FullName=<" + fullName + ">" + newLine);
                System.out.print("address1=<" + address1 + ">" + newLine);
                System.out.print("address2=<" + address2 + ">" + newLine);
                System.out.print("city=<" + city + ">" + newLine);
                System.out.print("state=<" + state + ">" + newLine);
                System.out.print("country=<" + country + ">" + " - ");
                System.out.print("postcode=<" + postcode + ">" + newLine);
                System.out.print("itemcodeWithQty=<" + itemCodeWithQty + ">" + newLine);

                System.out.println("Label = " + newLine + label);


                label = fullName + newLine;
                if (address1.length() > 0) {
                    label += address1 + newLine;
                }
                if (address2.length() > 0) {
                    label += address2 + newLine;
                }
                label += city + newLine + state + newLine + country
                        + " - " + postcode;
                if (!label.equals("")) {
                    LabelInfo li = new LabelInfo();
                    li.setAddress(label);
                    li.setItemCodeAndQuantity(itemCodeWithQty);
                    labels.add(li);
                    counter++;
                } else {
                    System.out.println("Error!! label is not created = " + (i + 1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        System.out.println("Total Labels Consolidated = " + labels.size());
        return labels;
    }

    public boolean printLables(ArrayList labels, String destFile) {
        return printLables(labels, destFile, false);
    }

    public boolean printLables(ArrayList labels, String destFile, boolean newFormat) {

        boolean retVal = true;
        if (!newFormat) {

            try {
                int totalLabels = labels.size();
                System.out.println("Total Labels to print - " + totalLabels);

                if (destFile == null || destFile.equalsIgnoreCase("")) {
                    System.out.println("Error!! Dest File Name is empty");
                    return false;
                }

                System.out.println("Creating empty output file");
                File output = new File(destFile);

                /*Write Excel File Data*/
                HSSFWorkbook hwb = new HSSFWorkbook();
                HSSFSheet sheet = hwb.createSheet("auto1");

                //set the format for sheet
                sheet.setMargin(HSSFSheet.BottomMargin, BOTTOMMARGIN_VAL);
                sheet.setMargin(HSSFSheet.TopMargin, TOPMARGIN_VAL);
                sheet.setMargin(HSSFSheet.LeftMargin, LEFTMARGIN_VAL);
                sheet.setMargin(HSSFSheet.RightMargin, RIGHTMARGIN_VAL);
                //sheet.setMargin(HSSFSheet.HeaderMargin, HEADERMARGIN_VAL);
                //sheet.setMargin(HSSFSheet.FooterMargin, FOOTERMARGIN_VAL);

                HSSFPrintSetup printSetup = sheet.getPrintSetup();
                printSetup.setHeaderMargin(HEADERMARGIN_VAL);
                printSetup.setPaperSize(PAPERSIZE);
                printSetup.setFooterMargin(FOOTERMARGIN_VAL);

                sheet.setColumnWidth(0, CELL_ITEM_WIDTH);
                sheet.setColumnWidth(1, CELL_ADDR_WIDTH);
                sheet.setColumnWidth(2, CELL_ITEM_WIDTH);
                sheet.setColumnWidth(3, CELL_ADDR_WIDTH);
                sheet.setDefaultRowHeight((short) ITEMLIST_CELL_HEIGHT_IN_POINTS);
                HSSFCellStyle cellAddrStyle = hwb.createCellStyle();
                HSSFCellStyle cellItemStyle = hwb.createCellStyle();

                HSSFFont cellFont = hwb.createFont();
                HSSFFont cellItemFont = hwb.createFont();

                //Bold character
                //cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                //Aerial font
                cellFont.setFontName(this.CELL_FONT_NAME);
                cellItemFont.setFontName(this.CELL_FONT_NAME);
                //Font Size 12
                cellFont.setFontHeightInPoints((short) this.CELL_FONT_SIZE);
                cellItemFont.setFontHeightInPoints((short) this.CELL_ITEMCODE_SIZE);


                //set cell font
                cellAddrStyle.setFont(cellFont);
                cellItemStyle.setFont(cellItemFont);
                //set cell alignment
                cellAddrStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
                cellAddrStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                cellItemStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                cellItemStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_BOTTOM);
                //cell wrap text
                cellAddrStyle.setWrapText(true);
                cellItemStyle.setWrapText(true);
                //set cell width & height

                //Print two array elements in one column
                int totalRows = (int) totalLabels / 2 + (int) totalLabels % 2;
                int labelCounter = 0;
                for (int rowCount = 0; rowCount < totalRows; rowCount++) {
                    HSSFRow row = sheet.createRow((short) rowCount);
                    row.setHeightInPoints(CELL_HEIGHT_IN_POINTS);
                    for (int colCount = 0; colCount < 2 && labelCounter < totalLabels; labelCounter++, colCount++) {
                        HSSFCell cell = row.createCell(colCount);
                        cell.setCellStyle(cellAddrStyle);
                        if ((labels.get(labelCounter) != null) && (((LabelInfo) labels.get(labelCounter)).getAddress() != null) && !((LabelInfo) labels.get(labelCounter)).getAddress().toString().equals("")) {
                            HSSFRichTextString richTextLabel = new HSSFRichTextString(((LabelInfo) labels.get(labelCounter)).getAddress().toString());
                            System.out.println("Labels in Rich Text format = " + richTextLabel);
                            cell.setCellValue(richTextLabel);
                        }

                    }
                }


                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(output);
                    hwb.write(fos);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.flush();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return retVal;
        } else {
            /*Start new format*/
            try {
                int totalLabels = labels.size();
                System.out.println("Total Labels to print - " + totalLabels);

                if (destFile == null || destFile.equalsIgnoreCase("")) {
                    System.out.println("Error!! Dest File Name is empty");
                    return false;
                }

                System.out.println("Creating empty output file");
                File output = new File(destFile);

                /*Write Excel File Data*/
                HSSFWorkbook hwb = new HSSFWorkbook();
                HSSFSheet sheet = hwb.createSheet("auto1");

                //set the format for sheet
                sheet.setMargin(HSSFSheet.BottomMargin, BOTTOMMARGIN_VAL);
                sheet.setMargin(HSSFSheet.TopMargin, TOPMARGIN_VAL);
                sheet.setMargin(HSSFSheet.LeftMargin, LEFTMARGIN_VAL);
                sheet.setMargin(HSSFSheet.RightMargin, RIGHTMARGIN_VAL);
                //sheet.setMargin(HSSFSheet.HeaderMargin, HEADERMARGIN_VAL);
                //sheet.setMargin(HSSFSheet.FooterMargin, FOOTERMARGIN_VAL);

                HSSFPrintSetup printSetup = sheet.getPrintSetup();
                printSetup.setHeaderMargin(HEADERMARGIN_VAL);
                printSetup.setPaperSize(PAPERSIZE);
                printSetup.setFooterMargin(FOOTERMARGIN_VAL);

                sheet.setColumnWidth(0, CELL_ITEM_WIDTH);
                sheet.setColumnWidth(1, CELL_ADDR_WIDTH);
                sheet.setColumnWidth(2, CELL_ITEM_WIDTH);
                sheet.setColumnWidth(3, CELL_ADDR_WIDTH);
                sheet.setDefaultRowHeight((short) CELL_HEIGHT);
                HSSFCellStyle cellAddrStyle = hwb.createCellStyle();
                HSSFCellStyle cellItemStyle = hwb.createCellStyle();

                HSSFFont cellFont = hwb.createFont();
                HSSFFont cellItemFont = hwb.createFont();

                //Bold character
                //cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                //Aerial font
                cellFont.setFontName(this.CELL_FONT_NAME);
                cellItemFont.setFontName(this.CELL_FONT_NAME);
                cellItemFont.setStrikeout(true);
                //Font Size 12
                cellFont.setFontHeightInPoints((short) this.CELL_FONT_SIZE);
                cellItemFont.setFontHeightInPoints((short) this.CELL_ITEMCODE_SIZE);
                //cellItemFont.setColor(HSSFColor.WHITE.index);


                //set cell font
                cellAddrStyle.setFont(cellFont);
                cellItemStyle.setFont(cellItemFont);
                //set cell alignment
                cellAddrStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
                cellAddrStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                cellItemStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                cellItemStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                cellItemStyle.setRotation(CELL_ITEMCODE_ROTATION);
                //cell wrap text
                cellAddrStyle.setWrapText(true);
                cellItemStyle.setWrapText(true);
                //cellItemStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                //cellItemStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

                //set cell width & height

                //Print two array elements in one column
                int totalRows = (int) totalLabels / 2 + (int) totalLabels % 2;
                int labelCounter = 0;
                for (int rowCount = 0; rowCount < totalRows; rowCount++) {
                    HSSFRow row = sheet.createRow((short) rowCount);
                    row.setHeightInPoints(CELL_HEIGHT_IN_POINTS);
                    for (int colCount = 0; colCount < 4 && labelCounter < totalLabels; colCount++) {
                        if ((colCount % 2) != 0) {//columns with address
                            HSSFCell cell = row.createCell(colCount);
                            cell.setCellStyle(cellAddrStyle);
                            if ((labels.get(labelCounter) != null) && (((LabelInfo) labels.get(labelCounter)).getAddress() != null) && !((LabelInfo) labels.get(labelCounter)).getAddress().toString().equals("")) {
                                HSSFRichTextString richTextLabel = new HSSFRichTextString(((LabelInfo) labels.get(labelCounter)).getAddress().toString());
                                System.out.println("Labels in Rich Text format = " + richTextLabel);
                                cell.setCellValue(richTextLabel);
                                labelCounter++;//only increase label counter when address is printed
                            }
                        } else {//columns with item details
                            HSSFCell cell = row.createCell(colCount);
                            cell.setCellStyle(cellItemStyle);
                            if ((labels.get(labelCounter) != null) && (((LabelInfo) labels.get(labelCounter)).getAddress() != null) && !((LabelInfo) labels.get(labelCounter)).getAddress().toString().equals("")) {
                                HSSFRichTextString richTextLabel = new HSSFRichTextString(((LabelInfo) labels.get(labelCounter)).getItemCodeAndQuantity().toString());
                                System.out.println("ItemCodeAndQuantity = " + richTextLabel);
                                cell.setCellValue(richTextLabel);
                            }
                        }

                    }
                }


                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(output);
                    hwb.write(fos);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.flush();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }



            return retVal;
        }

    }

    public String getOutputFileName(String persistenRoot, File origFile) {
        String outputFilename = persistantRoot + "output" + File.separator + Utils.getDate("ddmmyyyy") + "_" + origFile.getName();
        return outputFilename;
    }

    public String getItemListFileName(String persistenRoot, File origFile) {
        String outputFilename = persistantRoot + "records" + File.separator + "ItemList_" + Utils.getDate("ddmmyyyy") + "_" + origFile.getName();
        return outputFilename;
    }

    public String getJointFileName(String persistenRoot, File origFile) {
        String outputFilename = persistantRoot + "postageLabels" + File.separator + "label_" + Utils.getDate("ddmmyyyy") + "_" + origFile.getName();
        return outputFilename;
    }

    public boolean process() {
        System.out.println("Entry in process ");
        try {
            int counter = 0;
            boolean retVal = this.initialize();

            if (!retVal) {
                return false;
            }

            ArrayList buyers = new ArrayList();
            ArrayList tempBuyers = null;

            //get the file
            File processingDir = new File(persistantRoot);
            File[] files = processingDir.listFiles();
            File workingFile = null;
            File currentFile = null;
            int i = 0;
            for (; i < files.length; i++) {
                currentFile = files[i];
                if (currentFile.isDirectory()) {
                    continue;
                }
                if (!ifFileExist(currentFile.getName(), archiveFolder)) {
                    workingFile = currentFile;
                    System.out.println("Check if file is excel file...");
                    if (workingFile!= null && ifExcelFile(workingFile.getName())) {
                        destFileName = getOutputFileName(persistantRoot, workingFile);
                        destItemListFileName = getItemListFileName(persistantRoot, workingFile);
                        System.out.println("destfile name = " + destFileName);
                        System.out.println("destItemListFileName = " + destItemListFileName);
                        BuyerDetail detail = new BuyerDetail();
                        ExcelManager em = new ExcelManager();
                        //dto.setAttachmentFileName(workingFile.getName());

                        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(workingFile));
                        if (wb != null) {
                            em.setWorkBook(wb);

                            //change for processing multiple files - start
                            //buyers = this.processFile(em);
                            tempBuyers = this.processFile(em);
                            //if(tempBuyers is not null then append to existing buyers arraylist
                            if (tempBuyers != null && tempBuyers.size() > 0) {
                                //tempbuyers has items to append
                                if (buyers == null) {
                                    buyers = new ArrayList();
                                }
                                int itemCntr = 0;
                                for (itemCntr = 0; itemCntr < tempBuyers.size(); itemCntr++) {
                                    buyers.add(tempBuyers.get(itemCntr));
                                }
                                System.out.println("In itearation <" + i + 1 + "> Total Items added = <" + itemCntr + ">");

                            }
                        }
                    } else {
                        if(workingFile!= null){
                             workingFile.delete();
                        }
                        System.out.println("Since file \"" + (workingFile==null?"":workingFile.getName()) + "\" is not an Excel file So I deleted it.. is it ok??");
                    }
                } else {
                    System.err.println("Couldn't read " + (workingFile==null?"<workingfile is null>":workingFile.getAbsolutePath()) + " - " + (workingFile==null?"<working file is null>":workingFile.getName()));
                }
            }//end of for loop
            //change for processing multiple files - stop
            System.out.println("Totl files processed=<" + i + ">, Total records to process=<" + buyers.size() + ">");

            ArrayList itemList = createPostItemList(buyers, destItemListFileName);
            if (itemList == null || itemList.size() <= 0) {
                System.out.println("Error!! No item list created from this excel sheet");
            } else {
                boolean printSuccess = this.printPostItemList(itemList, destItemListFileName);
                if (printSuccess) {
                    this.doArchiving(workingFile.getName(), persistantRoot, archiveFolder);
                } else {
                    System.out.println("Error!! print item list failed"); 
                }
            }


            ArrayList labels = this.createLabel(buyers, destFileName);
            if (labels.size() <= 0) {
                System.out.println("Error!! No labels created from this excel sheet");
            } else {
                boolean printSuccess = this.printLables(labels, destFileName);
                if (printSuccess) {
                    //postpone archiving for later
                    //this.doArchiving(workingFile.getName(), persistantRoot, archiveFOlder);
                } else {
                    System.out.println("Error!! print label failed");
                }
            }

            //Adding logic to generate combined output labels
            System.out.println("current path = <" + new java.io.File(".").getCanonicalPath() + ">");
            String labelFileName = getJointFileName(persistantRoot, workingFile);
            System.out.println("labelFileName = <" + labelFileName + ">");
            ArrayList postageLabels = createPostageLables(buyers, destFileName + "_joint");
            boolean printSuccess = this.printLables(labels, labelFileName, true);

        } catch (Exception ex) {
            ex.printStackTrace();
            //this.sendMail(fromAddress, job_business_contact, mailSubject, ex.getMessage(), null, smtpServer, fromDisplayName);
            return false;
        }

        return true;
    }

    public boolean ifFileExist(String file, String archivePath) {
        boolean ifFound = false;
        File target = new File(archivePath + "\\" + file);
        if (target.exists()) {
            ifFound = true;
        }
        return ifFound;
    }

    public boolean ifExcelFile(String fileName) {
        boolean ifXlFile = false;
        if (fileName != null
                && ((fileName.indexOf(".xls") > -1)
                || (fileName.indexOf(".special") > -1))) {
            ifXlFile = true;
        }
        return ifXlFile;
    }

    private ArrayList processFile(ExcelManager dto) throws Exception {
        ArrayList buyers = new ArrayList();
        if (dto == null || dto.getWorkBook() == null) {
            System.out.println("Error!! workbook received is null. Please set work book before calling processing");
            return null;
        }


        try {
            HSSFWorkbook wb = dto.getWorkBook();
            HSSFSheet sheet = wb.getSheetAt(0);
            int totalRows = dto.totalRowsToProcess(sheet);
            System.out.println("Total rows found (including header, empty & footer rows) = " + totalRows);
            if (totalRows > MIN_ROWS_AVAILABLE) {
                System.out.println("Orders available to process - <" + (totalRows - MIN_ROWS_AVAILABLE) + ">");
                System.out.println("set totalrows to skip footer");
                totalRows = totalRows - MIN_ROWS_AVAILABLE;
            }
            //process all rows except header rows
            //for (int j = 0; j < totalRows; j++) {
            //skip header row
            for (int j = START_ROW; j < totalRows + START_ROW; j++) {

                HSSFRow row = sheet.getRow(j);
                HSSFCell cell = null;
                //process header row
                /*if (j == EMPTY_ROW_NO_BEFORE_HEADER) {
                 System.out.println("Skip empty row before header");
                 } else if (j == EMPTY_ROW_NO_AFTER_HEADER) {
                 System.out.println("Skip empty row after header");
                 } else */   /*if (j == HEADER_ROW_NO){
                 System.out.println("Processing Header Row");
                 BuyerDetail header = new BuyerDetail();
                 if (row != null) {
                 boolean retVal = header.loadRow(row);
                 if (!retVal) {
                 System.out.println("Error!! Can not extract header record");
                 continue;
                 } else {
                 System.out.println("Header = " + header.toString());
                 }
                 }


                 } else {/*Other than header records - i.e. actual records*/

                BuyerDetail record = new BuyerDetail();
                if (row != null) {
                    boolean retVal = record.loadRow(row);
                    if (!retVal) {
                        System.out.println("Error!! Can not extract values for row no " + j);
                        continue;
                    } else {
                        buyers.add(record);
                        System.out.println("Row(" + j + ") = " + record.toString());
                    }
                }

                //}
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error!! Exception raised");
            //throw new Exception("Schedular Error for job : Process TIAB SCP Response\n\nError Processing SCP response.\nFile Name: " + dto.getAttachmentFileName());
        }
        System.out.println("Total Rows added - " + buyers.size());
        return buyers;
    }

    public void doArchiving(String file, String source, String archive) {
        File archcheck = null;

        archcheck = new File(archive);
        if (!archcheck.exists() || !archcheck.isDirectory()) {
            archcheck.mkdirs();
        }
        File dest = new File(archive + "\\" + file);
        File orig = new File(source + "\\" + file);

        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(orig);
            to = new FileOutputStream(dest);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytesRead); // write

            }
            from.close();
            to.close();
            dest.setLastModified(orig.lastModified());
            System.out.println("File copied to archive directory");
            if (dest.exists() && dest.length() == orig.length()) {
                System.out.println("Both file are of equal size.. deleting the origional file");
                boolean ifDeleted = orig.delete();
                if (orig.exists()) {
                    orig.delete();
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {

        GenPostageLabel mainInst = new GenPostageLabel();
        //mainInst.init();
        boolean result = mainInst.process();
        if (result) {
            System.out.println("result generated successfully");
        } else {
            System.out.println("Failed to generated files");
        }
    }
}
